<template>
  <t-card>
    <t-space direction="vertical" style="width: 100%">
      <t-form v-show="showSearch" ref="queryRef" :data="queryParams" layout="inline" reset-type="initial" label-width="calc(4em + 12px)">
        <t-form-item label="客户ID" name="customerId">
          <t-input v-model="queryParams.customerId" placeholder="请输入客户ID" clearable @enter="handleQuery" />
        </t-form-item>
        <t-form-item label="产品ID" name="productId">
          <t-input v-model="queryParams.productId" placeholder="请输入产品ID" clearable @enter="handleQuery" />
        </t-form-item>
        <t-form-item label="优惠卷ID" name="couponId">
          <t-input v-model="queryParams.couponId" placeholder="请输入优惠卷ID" clearable @enter="handleQuery" />
        </t-form-item>
        <t-form-item label="数量" name="quantity">
          <t-input v-model="queryParams.quantity" placeholder="请输入数量" clearable @enter="handleQuery" />
        </t-form-item>
        <t-form-item label="单价" name="unitPrice">
          <t-input v-model="queryParams.unitPrice" placeholder="请输入单价" clearable @enter="handleQuery" />
        </t-form-item>
        <t-form-item label="总金额" name="totalAmount">
          <t-input v-model="queryParams.totalAmount" placeholder="请输入总金额" clearable @enter="handleQuery" />
        </t-form-item>
        <t-form-item label="订单日期" name="orderDate">
          <t-date-picker
            v-model="queryParams.orderDate"
            allow-input
            clearable
            placeholder="请选择订单日期"
          />
        </t-form-item>
        <t-form-item label="预计自取日期" name="estimatedPickupDate">
          <t-date-picker
            v-model="queryParams.estimatedPickupDate"
            allow-input
            clearable
            placeholder="请选择预计自取日期"
          />
        </t-form-item>
        <t-form-item label="自取地点" name="pickupLocation">
          <t-input v-model="queryParams.pickupLocation" placeholder="请输入自取地点" clearable @enter="handleQuery" />
        </t-form-item>
        <t-form-item label="收货人姓名" name="recipientName">
          <t-input v-model="queryParams.recipientName" placeholder="请输入收货人姓名" clearable @enter="handleQuery" />
        </t-form-item>
        <t-form-item label="联系电话" name="contactPhone">
          <t-input v-model="queryParams.contactPhone" placeholder="请输入联系电话" clearable @enter="handleQuery" />
        </t-form-item>
        <t-form-item label="电子邮箱" name="email">
          <t-input v-model="queryParams.email" placeholder="请输入电子邮箱" clearable @enter="handleQuery" />
        </t-form-item>
        <t-form-item label="付款方式" name="paymentMethod">
          <t-input v-model="queryParams.paymentMethod" placeholder="请输入付款方式" clearable @enter="handleQuery" />
        </t-form-item>
        <t-form-item label="特殊要求或备注" name="specialRequests">
          <t-input v-model="queryParams.specialRequests" placeholder="请输入特殊要求或备注" clearable @enter="handleQuery" />
        </t-form-item>
        <t-form-item label="商品来源说明" name="productOriginDescription">
          <t-input v-model="queryParams.productOriginDescription" placeholder="请输入商品来源说明" clearable @enter="handleQuery" />
        </t-form-item>
        <t-form-item label="完成自取确认时间" name="pickupConfirmationTime">
          <t-date-picker
            v-model="queryParams.pickupConfirmationTime"
            allow-input
            clearable
            placeholder="请选择完成自取确认时间"
          />
        </t-form-item>
        <t-form-item label-width="0px">
          <t-button theme="primary" @click="handleQuery">
            <template #icon> <search-icon /></template>
            搜索
          </t-button>
          <t-button theme="default" @click="resetQuery">
            <template #icon> <refresh-icon /></template>
            重置
          </t-button>
        </t-form-item>
      </t-form>

      <t-table
        v-model:column-controller-visible="columnControllerVisible"
        :loading="loading"
        hover
        row-key="orderId"
        :data="orderList"
        :columns="columns"
        :selected-row-keys="ids"
        select-on-row-click
        :pagination="pagination"
        :column-controller="{
          hideTriggerButton: true,
        }"
        @select-change="handleSelectionChange"
      >
        <template #topContent>
          <t-row>
            <t-col flex="auto">
              <t-button v-hasPermi="['xyyw:order:add']" theme="primary" @click="handleAdd">
                <template #icon> <add-icon /></template>
                新增
              </t-button>
              <t-button
                v-hasPermi="['xyyw:order:edit']"
                theme="default"
                variant="outline"
                :disabled="single"
                @click="handleUpdate()"
              >
                <template #icon> <edit-icon /> </template>
                修改
              </t-button>
              <t-button
                v-hasPermi="['xyyw:order:remove']"
                theme="danger"
                variant="outline"
                :disabled="multiple"
                @click="handleDelete()"
              >
                <template #icon> <delete-icon /> </template>
                删除
              </t-button>
              <t-button v-hasPermi="['xyyw:order:export']" theme="default" variant="outline" @click="handleExport">
                <template #icon> <download-icon /> </template>
                导出
              </t-button>
              <span class="selected-count">已选 {{ ids.length }} 项</span>
            </t-col>
            <t-col flex="none">
              <t-button theme="default" shape="square" variant="outline" @click="showSearch = !showSearch">
                <template #icon> <search-icon /> </template>
              </t-button>
              <t-button theme="default" variant="outline" @click="columnControllerVisible = true">
                <template #icon> <setting-icon /> </template>
                列配置
              </t-button>
            </t-col>
          </t-row>
        </template>
        <template #operation="{ row }">
          <t-space :size="8" break-line>
            <t-link v-hasPermi="['xyyw:order:query']" theme="primary" hover="color" @click.stop="handleDetail(row)">
              <browse-icon />详情
            </t-link>
            <t-link v-hasPermi="['xyyw:order:edit']" theme="primary" hover="color" @click.stop="handleUpdate(row)">
              <edit-icon />修改
            </t-link>
            <t-link v-hasPermi="['xyyw:order:remove']" theme="danger" hover="color" @click.stop="handleDelete(row)">
              <delete-icon />删除
            </t-link>
          </t-space>
        </template>
      </t-table>
    </t-space>

    <!-- 添加或修改订单对话框 -->
    <t-dialog
      v-model:visible="open"
      :header="title"
      destroy-on-close
      :close-on-overlay-click="false"
      width="500px"
      attach="body"
      :confirm-btn="{
        loading: buttonLoading,
      }"
      @confirm="orderRef.submit()"
    >
      <t-loading :loading="buttonLoading" size="small">
        <t-form
          ref="orderRef"
          label-align="right"
          :data="form"
          :rules="rules"
          label-width="calc(5em + 41px)"
          scroll-to-first-error="smooth"
          @submit="submitForm"
        >
          <t-form-item label="客户ID" name="customerId">
            <t-input-number v-model="form.customerId" placeholder="请输入" />
          </t-form-item>
          <t-form-item label="产品ID" name="productId">
            <t-input-number v-model="form.productId" placeholder="请输入" />
          </t-form-item>
          <t-form-item label="优惠卷ID" name="couponId">
            <t-input-number v-model="form.couponId" placeholder="请输入" />
          </t-form-item>
          <t-form-item label="数量" name="quantity">
            <t-input-number v-model="form.quantity" placeholder="请输入" />
          </t-form-item>
          <t-form-item label="单价" name="unitPrice">
            <t-input-number v-model="form.unitPrice" placeholder="请输入" />
          </t-form-item>
          <t-form-item label="总金额" name="totalAmount">
            <t-input-number v-model="form.totalAmount" placeholder="请输入" />
          </t-form-item>
          <t-form-item label="订单日期" name="orderDate">
            <t-date-picker
              v-model="form.orderDate"
              enable-time-picker
              allow-input
              clearable
              placeholder="请选择订单日期"
            />
          </t-form-item>
          <t-form-item label="预计自取日期" name="estimatedPickupDate">
            <t-date-picker
              v-model="form.estimatedPickupDate"
              enable-time-picker
              allow-input
              clearable
              placeholder="请选择预计自取日期"
            />
          </t-form-item>
          <t-form-item label="自取地点" name="pickupLocation">
            <t-input v-model="form.pickupLocation" placeholder="请输入自取地点" clearable />
          </t-form-item>
          <t-form-item label="收货人姓名" name="recipientName">
            <t-input v-model="form.recipientName" placeholder="请输入收货人姓名" clearable />
          </t-form-item>
          <t-form-item label="联系电话" name="contactPhone">
            <t-input v-model="form.contactPhone" placeholder="请输入联系电话" clearable />
          </t-form-item>
          <t-form-item label="电子邮箱" name="email">
            <t-input v-model="form.email" placeholder="请输入电子邮箱" clearable />
          </t-form-item>
          <t-form-item label="付款方式" name="paymentMethod">
            <t-input v-model="form.paymentMethod" placeholder="请输入付款方式" clearable />
          </t-form-item>
          <t-form-item label="特殊要求或备注" name="specialRequests">
            <t-textarea v-model="form.specialRequests" placeholder="请输入特殊要求或备注" />
          </t-form-item>
          <t-form-item label="商品来源说明" name="productOriginDescription">
            <t-textarea v-model="form.productOriginDescription" placeholder="请输入商品来源说明" />
          </t-form-item>
          <t-form-item label="完成自取确认时间" name="pickupConfirmationTime">
            <t-date-picker
              v-model="form.pickupConfirmationTime"
              enable-time-picker
              allow-input
              clearable
              placeholder="请选择完成自取确认时间"
            />
          </t-form-item>
        </t-form>
      </t-loading>
    </t-dialog>

    <!-- 订单详情 -->
    <t-dialog
      v-model:visible="openView"
      header="订单详情"
      placement="center"
      width="700px"
      attach="body"
      :footer="false"
    >
      <my-descriptions :loading="openViewLoading">
        <t-descriptions-item label="订单ID">{{ form.orderId }}</t-descriptions-item>
        <t-descriptions-item label="客户ID">{{ form.customerId }}</t-descriptions-item>
        <t-descriptions-item label="产品ID">{{ form.productId }}</t-descriptions-item>
        <t-descriptions-item label="优惠卷ID">{{ form.couponId }}</t-descriptions-item>
        <t-descriptions-item label="数量">{{ form.quantity }}</t-descriptions-item>
        <t-descriptions-item label="单价">{{ form.unitPrice }}</t-descriptions-item>
        <t-descriptions-item label="总金额">{{ form.totalAmount }}</t-descriptions-item>
        <t-descriptions-item label="订单日期">{{ parseTime(form.orderDate) }}</t-descriptions-item>
        <t-descriptions-item label="预计自取日期">{{ parseTime(form.estimatedPickupDate) }}</t-descriptions-item>
        <t-descriptions-item label="自取地点">{{ form.pickupLocation }}</t-descriptions-item>
        <t-descriptions-item label="订单状态">{{ form.orderStatus }}</t-descriptions-item>
        <t-descriptions-item label="收货人姓名">{{ form.recipientName }}</t-descriptions-item>
        <t-descriptions-item label="联系电话">{{ form.contactPhone }}</t-descriptions-item>
        <t-descriptions-item label="电子邮箱">{{ form.email }}</t-descriptions-item>
        <t-descriptions-item label="付款方式">{{ form.paymentMethod }}</t-descriptions-item>
        <t-descriptions-item label="特殊要求或备注" :span="2">{{ form.specialRequests }}</t-descriptions-item>
        <t-descriptions-item label="商品来源说明" :span="2">{{ form.productOriginDescription }}</t-descriptions-item>
        <t-descriptions-item label="创建时间">{{ parseTime(form.createTime) }}</t-descriptions-item>
        <t-descriptions-item label="完成自取确认时间">{{ parseTime(form.pickupConfirmationTime) }}</t-descriptions-item>
      </my-descriptions>
    </t-dialog>
  </t-card>
</template>
<script lang="ts" setup>
defineOptions({
  name: 'Order',
});
import {
  AddIcon,
  BrowseIcon,
  DeleteIcon,
  DownloadIcon,
  EditIcon,
  RefreshIcon,
  SearchIcon,
  SettingIcon,
} from 'tdesign-icons-vue-next';
import type { FormInstanceFunctions, FormRule, PageInfo, PrimaryTableCol, SubmitContext,  } from 'tdesign-vue-next';
import { computed, getCurrentInstance, ref } from 'vue';
import { ArrayOps } from '@/utils/array';

import type { XyywOrderForm, XyywOrderQuery, XyywOrderVo } from '@/api/xyyw/model/orderModel';
import { listOrder, getOrder, delOrder, addOrder, updateOrder } from '@/api/xyyw/order';

const { proxy } = getCurrentInstance();

const openView = ref(false);
const openViewLoading = ref(false);
const orderRef = ref<FormInstanceFunctions>();
const open = ref(false);
const buttonLoading = ref(false);
const title = ref('');
const orderList = ref<XyywOrderVo[]>([]);
const loading = ref(false);
const columnControllerVisible = ref(false);
const showSearch = ref(true);
const total = ref(0);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);

// 校验规则
const rules = ref<Record<string, Array<FormRule>>>({
  customerId: [{ required: true, message: '客户ID不能为空' }],
  productId: [{ required: true, message: '产品ID不能为空' }],
  couponId: [{ required: true, message: '优惠卷ID不能为空' }],
});

// 列显隐信息
const columns = ref<Array<PrimaryTableCol>>([
  { title: `选择列`, colKey: 'row-select', type: 'multiple', width: 50, align: 'center' },
  { title: `客户ID`, colKey: 'customerId', align: 'center' },
  { title: `产品ID`, colKey: 'productId', align: 'center' },
  { title: `优惠卷ID`, colKey: 'couponId', align: 'center' },
  { title: `数量`, colKey: 'quantity', align: 'center' },
  { title: `单价`, colKey: 'unitPrice', align: 'center' },
  { title: `总金额`, colKey: 'totalAmount', align: 'center' },
  { title: `订单日期`, colKey: 'orderDate', align: 'center', minWidth: 112, width: 180 },
  { title: `预计自取日期`, colKey: 'estimatedPickupDate', align: 'center', minWidth: 112, width: 180 },
  { title: `自取地点`, colKey: 'pickupLocation', align: 'center' },
  { title: `订单状态`, colKey: 'orderStatus', align: 'center' },
  { title: `收货人姓名`, colKey: 'recipientName', align: 'center' },
  { title: `联系电话`, colKey: 'contactPhone', align: 'center' },
  { title: `电子邮箱`, colKey: 'email', align: 'center' },
  { title: `付款方式`, colKey: 'paymentMethod', align: 'center' },
  { title: `特殊要求或备注`, colKey: 'specialRequests', align: 'center', ellipsis: true },
  { title: `商品来源说明`, colKey: 'productOriginDescription', align: 'center', ellipsis: true },
  { title: `创建时间`, colKey: 'createTime', align: 'center', minWidth: 112, width: 180 },
  { title: `完成自取确认时间`, colKey: 'pickupConfirmationTime', align: 'center', minWidth: 112, width: 180 },
  { title: `操作`, colKey: 'operation', align: 'center', width: 180 },
]);
// 提交表单对象
const form = ref<XyywOrderVo & XyywOrderForm>({});
// 查询对象
const queryParams = ref<XyywOrderQuery>({
  pageNum: 1,
  pageSize: 10,
  customerId: undefined,
  productId: undefined,
  couponId: undefined,
  quantity: undefined,
  unitPrice: undefined,
  totalAmount: undefined,
  orderDate: undefined,
  estimatedPickupDate: undefined,
  pickupLocation: undefined,
  orderStatus: undefined,
  recipientName: undefined,
  contactPhone: undefined,
  email: undefined,
  paymentMethod: undefined,
  specialRequests: undefined,
  productOriginDescription: undefined,
  pickupConfirmationTime: undefined,
});
// 分页
const pagination = computed(() => {
  return {
    current: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize,
    total: total.value,
    showJumper: true,
    onChange: (pageInfo: PageInfo) => {
      queryParams.value.pageNum = pageInfo.current;
      queryParams.value.pageSize = pageInfo.pageSize;
      getList();
    },
  };
});

/** 查询订单列表 */
function getList() {
  loading.value = true;
  listOrder(queryParams.value)
    .then((response) => {
      orderList.value = response.rows;
      total.value = response.total;
    })
    .finally(() => (loading.value = false));
}

// 表单重置
function reset() {
  form.value = {};
  proxy.resetForm('orderRef');
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef');
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection: Array<string | number>) {
  ids.value = selection;
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = '添加订单';
}

/** 详情按钮操作 */
function handleDetail(row: XyywOrderVo) {
  reset();
  openView.value = true;
  openViewLoading.value = true;
  const orderId = row.orderId;
  getOrder(orderId).then((response) => {
    form.value = response.data;
    openViewLoading.value = false;
  });
}

/** 修改按钮操作 */
function handleUpdate(row?: XyywOrderVo) {
  buttonLoading.value = true;
  reset();
  open.value = true;
  title.value = '修改订单';
  const orderId = row?.orderId || ids.value.at(0);
  getOrder(orderId).then((response) => {
    buttonLoading.value = false;
    form.value = response.data;
  });
}

/** 提交表单 */
function submitForm({ validateResult, firstError }: SubmitContext) {
  if (validateResult === true) {
    buttonLoading.value = true;
    const msgLoading = proxy.$modal.msgLoading('提交中...');
    if (form.value.orderId) {
      updateOrder(form.value)
        .then(() => {
          proxy.$modal.msgSuccess('修改成功');
          open.value = false;
          getList();
        })
        .finally(() => {
          buttonLoading.value = false;
          proxy.$modal.msgClose(msgLoading);
        });
    } else {
      addOrder(form.value)
        .then(() => {
          proxy.$modal.msgSuccess('新增成功');
          open.value = false;
          getList();
        })
        .finally(() => {
          buttonLoading.value = false;
          proxy.$modal.msgClose(msgLoading);
        });
    }
  } else {
    proxy.$modal.msgError(firstError);
  }
}

/** 删除按钮操作 */
function handleDelete(row?: XyywOrderVo) {
  const orderIds = row?.orderId || ids.value;
  proxy.$modal.confirm(`是否确认删除订单编号为${orderIds}的数据项？`, () => {
    const msgLoading = proxy.$modal.msgLoading('正在删除中...');
    return delOrder(orderIds)
      .then(() => {
        ids.value = ArrayOps.fastDeleteElement(ids.value, orderIds);
        getList();
        proxy.$modal.msgSuccess('删除成功');
      })
      .finally(() => {
        proxy.$modal.msgClose(msgLoading);
      });
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    'xyyw/order/export',
    {
      ...queryParams.value,
    },
    `order_${new Date().getTime()}.xlsx`,
  );
}

getList();
</script>
